package com.dykj.fireFighting.web.service.impl;

import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.base.file.service.DataFilesService;
import com.dykj.fireFighting.api.base.file.service.OfficeService;
import com.dykj.fireFighting.web.mongodb.GridFSRepository;
import com.dykj.fireFighting.web.utils.ExportUtils;
import com.dykj.fireFighting.web.utils.MergeCommand;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.bson.types.ObjectId;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@DubboService
@Transactional(rollbackFor = Exception.class)
public class OfficeServiceImpl  implements OfficeService {
    @Autowired
    private DocumentConverter documentConverter;
    @Autowired
    private DataFilesService dataFilesService;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    static{
        XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
    }
    /**
     *  导出Excel
     * @param map
     * @param modelName
     * @param returnName
     * @param response
     */
    @Override
    public void exportExcel(Map<String, Object> map, String modelName, String returnName, HttpServletResponse response) {
        try {

            ExportUtils.exportExcel(map,modelName,returnName,response);

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public String saveEXceltoMongo(Map<String, Object> map,String picturePath,String modelName, String returnName) throws Exception {

        InputStream is= Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplate/"+modelName);

        XLSTransformer transformer = new XLSTransformer();
        XSSFWorkbook workBook = (XSSFWorkbook) transformer.transformXLS(is, map);
        XSSFSheet sheet =workBook.getSheetAt(0);
        XSSFDrawing patriarch = sheet.createDrawingPatriarch();
       /* 改excel模板的时候 不要随意拉动单元格长度 否则图片会受到影响*/
        int morenchang=72;//单元格长度
        int morenkuan=18;
        int chushix=0;
        int chushiy=5;
        if(null !=picturePath && StringUtils.isNotBlank(picturePath)){
            String[] split = picturePath.split(",");
            for (int i = 0; i <split.length ; i++) {
                DataFiles dataFiles = dataFilesService.getById(split[i]);
                InputStream imgInput = dataFilesService.getFile(dataFiles.getFileMongoId());
                if(null !=imgInput){
                    BufferedImage bufferImg= ImageIO.read(imgInput);
                    int chang=(bufferImg.getWidth()/morenchang)+((bufferImg.getWidth()%morenchang>(morenchang/2)?1:0));
                    int kuan=(bufferImg.getHeight()/morenkuan)+((bufferImg.getHeight()%morenkuan>(morenkuan/2)?1:0));

                    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                    ImageIO.write(bufferImg, "png", byteArrayOut);
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
                            (short) chushix, chushiy, (short) (chushix+chang), (chushiy+kuan));
                    chushiy=chushiy+kuan;
                    patriarch.createPicture(anchor, workBook.addPicture(byteArrayOut
                            .toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
                    byteArrayOut.flush();
                    byteArrayOut.close();
                }

            }
        }
        /*else {
            InputStream imgInput= Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplate/zw.png");
            ExportUtils.drawPic(imgInput,workBook,chushix,chushiy);
        }*/

        ByteArrayOutputStream os=new ByteArrayOutputStream();
       // JxlsHelper.getInstance().setUseFastFormulaProcessor(false).processTemplate(is, os, context);

        workBook.write(os);

        String id =dataFilesService.uploadFile( new ByteArrayInputStream(os.toByteArray()),os.toByteArray().length,returnName,"application/vnd.ms-excel");

        is.close();
        os.close();
        //bis.close();
        return id.toString();
    }



    @Override
    public String excelToPdfSave(Map<String, Object> map, String modelName, String returnName) throws Exception{
        InputStream is= Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplate/"+modelName);
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        Context context=new Context();
        for(Map.Entry<String, Object> entry : map.entrySet()){
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            context.putVar(mapKey,mapValue);

        }
        JxlsHelper.getInstance().setUseFastFormulaProcessor(false).processTemplate(is, os, context);
        ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        documentConverter.convert(bis)
                .as(DefaultDocumentFormatRegistry.XLSX)
                .to(bos)
                .as(DefaultDocumentFormatRegistry.PDF)
                .execute();
        String id =dataFilesService.uploadFile( new ByteArrayInputStream(bos.toByteArray()),bos.toByteArray().length,returnName,"application/pdf");
        try {
            is.close();
            os.close();
            bis.close();
            bos.close();
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return id;

    }

}
